<?php

namespace app\api\model;


use think\Model;
use \app\api\model\WorkProcess;

class OrderPaymentNodes extends Model
{
    protected $table = 'order_payment_nodes';
    protected $connection = 'database.zong';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';            //数据添加的时候，create_time 这个字段不自动写入时间戳
    protected $updateTime = false;
    public static $snakeAttributes = false;
    
    /**
     * 生成订单支付节点
     * bcadd  精确结算加法
     * bcsub   精确计算减法
     * bcmul   精确计算乘法
     * bcdiv    精确计算除法
     */
    public function generateOrderPaymentNodes(array $data): array
    {
        $order_payment_nodes = [];
        $time                = time();
        // 订单支付节点全款金额（合同总金额）
        $all_amount_main   = strval($data['MainMaterialMoney']);
        $all_amount_agency = strval($data['agencyMoney']);
        // 按订单签约的付款方式，生成订单支付节点
        $pay_method = $this->getOrderPayMethod($data);
        switch ($pay_method['pay_method']) {
            case 1:
                $node_status = 1;
                if ($pay_method['pay_amount_time_1'] == 1) {
                    $node_status = 2;
                }
                $order_payment_nodes[1] = [
                    'order_id' => $data['order_id'],
                    'node_title' => '全款',
                    'node_money' => bcadd($all_amount_main, $all_amount_agency, 2),
                    'node_status' => $node_status,
                    'create_time' => $time,
                    'node_code' => 1,
                    'node_pay_tips' => $pay_method['pay_amount_time_1_tips'],
                    'node_money_agency' => $all_amount_agency,
                    'node_money_main' => $all_amount_main,
                ];
                break;
            case 2:
                $node_status = 1;
                if ($pay_method['pay_amount_time_1'] == 1) {
                    $node_status = 2;
                }
                $node_money_main        = (string)round(strval($all_amount_main)*strval($pay_method['pay_amount_scale_1']), 2);
                $node_money_agency      = (string)round(strval($all_amount_agency)*strval($pay_method['pay_amount_scale_1']), 2);
                $order_payment_nodes[1] = [
                    'order_id' => $data['order_id'],
                    'node_title' => '开工款',
                    'node_money' => bcadd($node_money_main, $node_money_agency, 2),
                    'node_status' => $node_status,
                    'create_time' => $time,
                    'node_code' => 1,
                    'node_pay_tips' => $pay_method['pay_amount_time_1_tips'],
                    'node_money_agency' => $node_money_agency,
                    'node_money_main' => $node_money_main,
                ];
                
                $node_money_main        = bcsub(strval($all_amount_main), strval($order_payment_nodes[1]['node_money_main']), 2);
                $node_money_agency      = bcsub(strval($all_amount_agency), strval($order_payment_nodes[1]['node_money_agency']), 2);
                $order_payment_nodes[2] = [
                    'order_id' => $data['order_id'],
                    'node_title' => '完工款',
                    'node_money' => bcadd($node_money_main, $node_money_agency, 2),
                    'node_status' => 1,
                    'create_time' => $time,
                    'node_code' => 3,
                    'node_pay_tips' => $pay_method['pay_amount_time_3_tips'],
                    'node_money_agency' => $node_money_agency,
                    'node_money_main' => $node_money_main,
                ];
                break;
            case 3:
                $node_status = 1;
                if ($pay_method['pay_amount_time_1'] == 1) {
                    $node_status = 2;
                }
                $node_money_main        = (string)round(strval($all_amount_main)*strval($pay_method['pay_amount_scale_1']), 2);
                $node_money_agency      = (string)round(strval($all_amount_agency)*strval($pay_method['pay_amount_scale_1']), 2);
                $order_payment_nodes[1] = [
                    'order_id' => $data['order_id'],
                    'node_title' => '开工款',
                    'node_money' => bcadd($node_money_main, $node_money_agency, 2),
                    'node_status' => $node_status,
                    'create_time' => $time,
                    'node_code' => 1,
                    'node_pay_tips' => $pay_method['pay_amount_time_1_tips'],
                    'node_money_agency' => $node_money_agency,
                    'node_money_main' => $node_money_main,
                ];
                
                $node_money_main        = (string)round(strval($all_amount_main)*strval($pay_method['pay_amount_scale_2']), 2);
                $node_money_agency      = (string)round(strval($all_amount_agency)*strval($pay_method['pay_amount_scale_2']), 2);
                $order_payment_nodes[2] = [
                    'order_id' => $data['order_id'],
                    'node_title' => '中期款',
                    'node_money' => bcadd($node_money_main, $node_money_agency, 2),
                    'node_status' => 1,
                    'create_time' => $time,
                    'node_code' => 2,
                    'node_pay_tips' => $pay_method['pay_amount_time_2_tips'],
                    'node_money_agency' => $node_money_agency,
                    'node_money_main' => $node_money_main,
                ];
                
                $node_money_main        = bcsub(strval($all_amount_main), bcadd($order_payment_nodes[1]['node_money_main'], $order_payment_nodes[2]['node_money_main'], 2), 2);
                $node_money_agency      = bcsub(strval($all_amount_agency), bcadd($order_payment_nodes[1]['node_money_agency'], $order_payment_nodes[2]['node_money_agency'], 2), 2);
                $order_payment_nodes[3] = [
                    'order_id' => $data['order_id'],
                    'node_title' => '完工款',
                    'node_money' => bcadd($node_money_main, $node_money_agency, 2),
                    'node_status' => 1,
                    'create_time' => $time,
                    'node_code' => 3,
                    'node_pay_tips' => $pay_method['pay_amount_time_3_tips'],
                    'node_money_agency' => $node_money_agency,
                    'node_money_main' => $node_money_main,
                ];
                break;
        }
        
        // 生成订单支付节点，定金
        if ($data['main_deposit'] == 1 && $data['ding'] > 0) {
            // 定金支付节点,主合同所占节点金额
            if ($order_payment_nodes[1]['node_money_main'] >= $data['ding']) {
                $node_money_main = $data['ding'];
            } else {
                $node_money_main = $order_payment_nodes[1]['node_money_main'];
            }
            //  定金支付节点,代购合同所占节点金额
            $node_money_agency = bcsub($data['ding'], $node_money_main, 2);
            
            // 从第一笔款中扣出来定金
            $order_payment_nodes[1]['node_money']        = bcsub(strval($order_payment_nodes[1]['node_money']), strval($data['ding']), 2);
            $order_payment_nodes[1]['node_money_main']   = bcsub(strval($order_payment_nodes[1]['node_money_main']), strval($node_money_main), 2);
            $order_payment_nodes[1]['node_money_agency'] = bcsub(strval($order_payment_nodes[1]['node_money_agency']), strval($node_money_agency), 2);
            
            // 主合同金额大于等于定金时，定金分配给主合同金额
            $order_payment_nodes[0] = [
                'order_id' => $data['order_id'],
                'node_title' => '定金',
                'node_money' => $data['ding'],
                'node_status' => 2,
                'create_time' => $time,
                'node_code' => 0,
                'node_pay_tips' => "请在 签约当日 完成支付，保证施工正常。",
                'node_money_agency' => $node_money_agency,
                'node_money_main' => $node_money_main,
            ];
        }
        $order_payment_nodes = (new workProcess)::arraySort($order_payment_nodes, 'node_code', SORT_ASC);
        $node_pay_sort       = 0;
        foreach ($order_payment_nodes as $k => $v) {
            $order_payment_nodes[$k]['node_pay_sort'] = $node_pay_sort++;
        }
        $order_payment_nodes = array_values($order_payment_nodes);
        
        $orderPaymentNodesID = $this->saveAll($order_payment_nodes);
        return $orderPaymentNodesID;
        
    }
    
    /**
     * 获取订单支付节点的付款方式
     *
     * @param array $data 生成合同的数据，来源于getSignInfoByOrderId方法返回的数据
     * @author hcg<532508307@qq.com>
     */
    public function getOrderPayMethod(array $data): array
    {
        $pay_method = [
            // 付款方式 1:一次性收款 2:首尾两次收款，3：首中尾三次收款
            'pay_method' => $data['main_pay_once'],
            // 第一次付款比例（0.5表示50%）
            'pay_amount_scale_1' => $data['main_pay_type'],
            // 第一次付款时间（1签合同当日、2开工当日）
            'pay_amount_time_1' => $data['main_mode_type'],
            // 第二次付款比例（0.5表示50%）
            'pay_amount_scale_2' => $data['main_pay_type1'],
            // 第三次付款比例（0.5表示50%）
            'pay_amount_scale_3' => $data['main_pay_type2'],
        ];
        
        $pay_method['pay_amount_time_tips'] = [
            'pay_amount_time_1_tips' => $data['main_mode_type_txt'] ?? '',
            'pay_amount_time_2_tips' => $data['main_mode_type1_txt'] ?? '',
            'pay_amount_time_3_tips' => $data['main_mode_type2_txt'] ?? '',
        ];
        
        // 支付节点提示信息
        $pay_method['pay_amount_time_1_tips'] = "请在 {$pay_method['pay_amount_time_tips']['pay_amount_time_1_tips']} 完成支付，保证施工正常。";
        $pay_method['pay_amount_time_2_tips'] = "请在 {$pay_method['pay_amount_time_tips']['pay_amount_time_2_tips']} 完成后支付，保证施工正常。";
        $pay_method['pay_amount_time_3_tips'] = "请在 {$pay_method['pay_amount_time_tips']['pay_amount_time_3_tips']} 完成支付，保证施工正常。";
        
        return $pay_method;
    }
    
    public function ListFind($orderId)
    {
        
        $count               = 0;
        $order_payment_nodes = $this
            ->join('payment', 'payment.payment_id=order_payment_nodes.payment_id', 'left')
            ->join('order', 'order.order_id=order_payment_nodes.order_id', 'left')
            ->join('order_setting', 'order.order_id=order_setting.order_id', 'left')
            ->join('personal', 'order.tui_jian=personal.personal_id', 'left')
            ->join('contract', 'contract.orders_id=order.order_id', 'left')
            ->where('order_payment_nodes.order_id', $orderId)
            ->where('order_payment_nodes.node_money', ">",0)
            ->field('order_payment_nodes.node_title,order_payment_nodes.node_pay_sort,order_payment_nodes.id as nodeID,order_payment_nodes.node_money,to_examine,order_payment_nodes.node_status,order_payment_nodes.payment_id,order_payment_nodes.node_pay_tips,payment.weixin,payment.success,trigger_time,payment.cleared_time as clearedTime,payment.uptime,node_code,id,if(order_setting.payment_type=3,1,0) as isNeedPaper,order_setting.payment_switch_1')
            ->order('order_payment_nodes.node_pay_sort asc')
            ->select();
        foreach ($order_payment_nodes as $k => $li) {
            $order_payment_nodes[$k]['title']      = '';
            $order_payment_nodes[$k]['state']      = 0;
            $order_payment_nodes[$k]['stateTitle'] = '未到节点-可付款';
            $order_payment_nodes[$k]['current'] = 0;
            if (!empty($order_payment_nodes[$k]['trigger_time'])) {
                $order_payment_nodes[$k]['trigger_time'] = floor((time() - $order_payment_nodes[$k]['trigger_time']) / (3600 * 24));
            }
            if ($li['payment_id'] != 0 && (($li['weixin'] == 6 || $li['weixin'] == 8 || $li['weixin'] == 1) && !empty($li['clearedTime'])) || ($li['weixin'] == 2 && $li['success'] == 2 && !empty($li['weixin'])) || ($li['weixin'] != 6 && $li['weixin'] != 8 && $li['weixin'] != 1 && !empty($li['weixin']) && $li['weixin'] != 2)) {
                $title='';
                if ($li['weixin'] == 6 || $li['weixin'] == 8 || $li['weixin'] == 1) {
                    $order_payment_nodes[$k]['clearedTime'] = !empty($li['clearedTime']) ? date('Y-m-d H:i:s', $li['clearedTime']) : '';
                } else {
                    $order_payment_nodes[$k]['clearedTime'] = !empty($li['uptime']) ? date('Y-m-d H:i:s', $li['uptime']) : '';
                }
                if(empty($li['clearedTime'])){
                    $title='入账处理中';
                }
                $order_payment_nodes[$k]['state']      = 1;
                $order_payment_nodes[$k]['stateTitle'] = '完成'.$title;
            }
            if ((( $li['payment_id'] == 0) || ($li['payment_id'] != 0 && $li['success'] == 3) || ($order_payment_nodes[$k]['node_status'] == 2 && $li['payment_id'] != 0 && $li['weixin'] == 2 && $li['success'] == 1) || (($li['weixin'] == 6 || $li['weixin'] == 8 || $li['weixin'] == 1) && empty($li['clearedTime']))) && $order_payment_nodes[$k]['trigger_time'] == 0) {
                $order_payment_nodes[$k]['state']      = 2;
                $order_payment_nodes[$k]['stateTitle'] = '已到节点-待付款';
                
            }
            if ((($li['payment_id'] == 0) || ($li['payment_id'] != 0 && $li['success'] == 3) || (($li['weixin'] == 6 || $li['weixin'] == 8 || $li['weixin'] == 1) && empty($li['clearedTime']))) && $order_payment_nodes[$k]['trigger_time'] > 0) {
                $order_payment_nodes[$k]['state']         = 3;
                $order_payment_nodes[$k]['stateTitle']    = '超期提醒';
                $order_payment_nodes[$k]['node_pay_tips'] = '已超出约定付款日' . $order_payment_nodes[$k]['trigger_time'] . '天,请及时付款';
            }
            if ($li['node_code'] != 0) {
                $count += 1;
            }
            $order_payment_nodes_log = db('order_payment_nodes_log', config('database.zong'))->where('order_payment_nodes_id', $li['id'])->select();
            if (!empty($order_payment_nodes_log)) {
                $order_payment_nodesMoney = $order_payment_nodes_log[count($order_payment_nodes_log) - 1]['node_money_after'] - $order_payment_nodes_log[0]['node_money_before'];
                if ($order_payment_nodesMoney > 0) {
                    $order_payment_nodes[$k]['title'] = '包含增项' . $order_payment_nodesMoney . '元';
                } else {
                    $order_payment_nodes[$k]['title'] = '包含减项' . $order_payment_nodesMoney . '元';
                }
                
            }
            unset($order_payment_nodes[$k]['payment_id'], $order_payment_nodes[$k]['weixin'], $order_payment_nodes[$k]['success'], $order_payment_nodes[$k]['node_status']);
        }
        return ['count'=>$count,'order_payment_nodes'=>$order_payment_nodes];
    }
    
    
}
